package com.diaoyanbao.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * 文件处理支持类
 * 
 * @author dingxs
 */
public final class FileSupport {
    /**
     * 递归得到目标文件夹下的文件
     * 
     * @param file
     * @param filter
     * @param filepathList
     * @return
     */
    public static List<String> getChildrenFilepath(File file, FileFilter filter, List<String> filepathList) {
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            for (File childFile : childFiles) {
                getChildrenFilepath(childFile, filter, filepathList);
            }
        } else {
            if (filter != null) {
                if (filter.isInTypes(file.getName())) {
                    filepathList.add(file.getPath());
                }
            } else {
                filepathList.add(file.getPath());
            }
        }
        return filepathList;
    }

    /**
     * 得到去除公共部分的文件名
     * 
     * @param orignal
     * @param truncate
     * @return
     */
    public static String truncateFileName(String orignal, String common) {
        if (common == null) {
            return orignal.substring(0, orignal.lastIndexOf("."));
        } else {
            return orignal.substring(common.length(), orignal.lastIndexOf("."));
        }
    }

    /**
     * 得到文件的md5检验值
     * 
     * @param filename
     * @return
     */
    public static String getFileMd5CheckSum(String filename) throws IOException, NoSuchAlgorithmException {
        InputStream fis = new FileInputStream(filename);
        byte[] buffer = new byte[1024];
        MessageDigest alogrithm = MessageDigest.getInstance("MD5");
        int numRead = 0;
        do {
            numRead = fis.read(buffer);
            if (numRead > 0) {
                alogrithm.update(buffer, 0, numRead);
            }
        } while (numRead != -1);
        fis.close();
        byte[] checksum = alogrithm.digest();
        String result = "";
        for (int i = 0; i < checksum.length; i++) {
            result += Integer.toString((checksum[i] & 0xff) + 0x100, 16).substring(1);
        }
        return result;
    }
}
